package com.cooper.service.item;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cooper.constants.ResourceConstants;
import com.cooper.core.JsonResult;
import com.cooper.dao.item.ItemStatDAO;
import com.cooper.entity.ItemStatEntity;
import com.cooper.entity.LikeDetailEntity;
import com.cooper.entity.UserInfo;
import com.cooper.util.Controllers;

@Service
public class ItemStatService {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private LikeDetailService likeDetailService;
	
	@Autowired
	private ItemStatDAO itemStatDao;
	
	public Long saveEntity(ItemStatEntity entity) throws Exception{
		return this.itemStatDao.saveEntity(entity);
	}
	
	public JsonResult like(LikeDetailEntity likeDetail, UserInfo userInfo) throws Exception{
		JsonResult json = new JsonResult();
		LikeDetailEntity detailEntity = this.likeDetailService.getEntityByClientIp(
				ResourceConstants.LikeOrigin.ITEM_LIKE, likeDetail.getOuterId(), likeDetail.getClientIp());
		if(null != detailEntity){
			json.setMessage("Don't repeat it with same ip address {0}.", likeDetail.getClientIp());
		} else {
			this.itemStatDao.like(likeDetail.getOuterId());
			likeDetail.setOrigin(ResourceConstants.LikeOrigin.ITEM_LIKE);
			likeDetail.setScore(1);
			if(null != userInfo){
				likeDetail.setUserId(userInfo.getId());
				Controllers.prepareEntityForDataSaving(likeDetail, userInfo, false);
			}
			this.likeDetailService.saveEntity(likeDetail);
			
			json.setSuccess(true);
		}
		
		return json;
	}
	
	public JsonResult unlike(LikeDetailEntity likeDetail, UserInfo userInfo) throws Exception{
		JsonResult json = new JsonResult();
		LikeDetailEntity detailEntity = this.likeDetailService.getEntityByClientIp(
				ResourceConstants.LikeOrigin.ITEM_LIKE, likeDetail.getOuterId(), likeDetail.getClientIp());
		if(null != detailEntity){
			json.setMessage("Don't repeat it with same ip address {0}.", likeDetail.getClientIp());
		} else {
			this.itemStatDao.unlike(likeDetail.getOuterId());
			likeDetail.setOrigin(ResourceConstants.LikeOrigin.ITEM_LIKE);
			likeDetail.setScore(-1);
			if(null != userInfo){
				likeDetail.setUserId(userInfo.getId());
				Controllers.prepareEntityForDataSaving(likeDetail, userInfo, false);
			}
			this.likeDetailService.saveEntity(likeDetail);
			
			json.setSuccess(true);
		}
		return json;
	}
	
	public void soldOut(Long itemId) throws Exception{
		this.itemStatDao.soldOut(itemId);
	}

}
